package com.demo.dao;

import com.demo.dao.mapper.SmsVerifyCodeMapper;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SmsCodeDao extends BaseDao{
    private static final String ENVIRONMENT_HOMER = "HOMER";
    private static final String ENVIRONMENT_HP = "HP";
    private static final String ENVIRONMENT_CU = "CU";

    // 查询 用户是否到达发送短信最大限制，是否被锁
    public Boolean isBlockSendSmsCode(String personId) {
        boolean isBlock = false;
        List<String> offerList = new ArrayList<String>();

        try (SqlSession session = openSession(ENVIRONMENT_CU)){
            SmsVerifyCodeMapper mapper = session.getMapper(SmsVerifyCodeMapper.class);
            offerList = mapper.selectPersonBlockStatus(personId, projectSettings.getProperty("environment"));
            if (offerList.size() > 0) {
                isBlock = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return isBlock;
    }

    public String selectSmsCodeFromHomer(String strategyPhoneNumber) {
        List<String> smsCodeLine = new ArrayList<String>();
        String smsCode = null;

        try (SqlSession session = openSession(ENVIRONMENT_HOMER)){
            SmsVerifyCodeMapper mapper = session.getMapper(SmsVerifyCodeMapper.class);
            smsCodeLine = mapper.selectSmsCodeFromHomer(strategyPhoneNumber);

            // 获取最新的验证码
            smsCode = regex(smsCodeLine.get(0));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return smsCode;
    }

    public String selectSmsCodeHP(String authorizationId) {
        String smsCode = null;

        try (SqlSession session = openSession(ENVIRONMENT_HP)){
            SmsVerifyCodeMapper mapper = session.getMapper(SmsVerifyCodeMapper.class);
            smsCode = mapper.selectSmsCodeFromHp(authorizationId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return smsCode;
    }

    /**
     * @Name: regex
     * @Description: 通过正则表达式获取短信验证码
     */
    protected String regex(String line) {

        String pattern = "(\\d+)(.*)";
        // 创建 Pattern 对象
        Pattern r = Pattern.compile(pattern);

        // 现在创建 matcher 对象
        Matcher m = r.matcher(line);
        if (m.find()) {
            return m.group(1);
        } else {
            System.out.println("NO MATCH");
        }
        return null;
    }
}
